package cn.mabach.oauth2.authentication;

import cn.mabach.oauth2.properties.props.LoginType;
import cn.mabach.oauth2.properties.SecurityProperties;
import cn.mabach.oauth2.utils.RS;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


/**
 * 配置认证失败处理器器
 */
@Component
@Slf4j
public class CustomAuthenticationFailureHandler extends SimpleUrlAuthenticationFailureHandler {

    @Autowired
    private SecurityProperties securityProperties;
    /**
     *
     * @param exception 认证失败时抛出异常
     */
    @Override
    public void onAuthenticationFailure(HttpServletRequest request,
                                        HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {

        log.info("登陆失败");
//返回类型是JSON
        if (LoginType.JSON.equals(securityProperties.getBrowser().getLoginPage())){
            response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().write(JSON.toJSONString(RS.error(exception.getMessage())));
        }


//       返回类型是重定向
        // 获取上一次请求路径
//        String referer = request.getHeader("Referer");
//        String lastUrl = StringUtils.substringBefore(referer, "?");
//        super.setDefaultFailureUrl(lastUrl+"?error");
//        super.onAuthenticationFailure(request, response, exception);

        String referer = request.getRequestURL().toString();
        log.info("登录请求是：{}",referer);
//        response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().write(JSON.toJSONString(RS.error(exception.getMessage())));
        }

    }

